package com.example.mapp.buildSql;

import com.example.ext.entity.ExtInformation;
import org.apache.ibatis.jdbc.SQL;

/**
 * Created by simon on 2017/10/12.
 */
public class InformationMappSql {

    public String queryList(ExtInformation extInformation){

        String select = "t1.*, t2.user_name as createUserName, case when t1.create_party_id = t3.parent_id then t4.party_name else t3.party_name end as createPartyName";
        String table =" information t1 " +
                "left join sys_user t2 on t1.create_user_id=t2.id " +
                "left join party t3 on t1.create_party_id=t3.id " +
                "left join party t4 on t3.parent_id=t4.id ";
        String whereParam="";


        if(extInformation.getCreatePartyId()!=null){
            whereParam+=" and (t1.create_party_id = #{createPartyId} ";
            if(extInformation.getParentId()!=null){
                whereParam+=" or t1.create_party_id = #{parentId}) ";
            } else {
            	whereParam+=" ) ";
            }
        }
        if (extInformation.getUserId() != null) {
        	whereParam += " and not exists (select 1 from sys_user p1 where t1.create_time>p1.update_time and p1.id=#{userId})";
        }

        String where = " 1=1 "+whereParam;
        String sql = new SQL(){{
            SELECT(select);
            FROM(table);
            WHERE(where);
            ORDER_BY("t1.create_time desc");
        }
        }.toString();

        int from = (extInformation.getCurrentPage()-1)*extInformation.getPageSize();
        String limit = " limit "+from+","+extInformation.getPageSize();

        return sql+limit;
    }

    public String countList(ExtInformation extInformation){

        String select = "count(t1.id)";
        String table =" information t1 " +
                "left join sys_user t2 on t1.create_user_id=t2.id " +
                "left join party t3 on t1.create_party_id=t3.id " +
                "left join party t4 on t3.parent_id=t4.id ";
        String whereParam="";


        if(extInformation.getCreatePartyId()!=null){
            whereParam+=" and (t1.create_party_id = #{createPartyId} ";
            if(extInformation.getParentId()!=null){
                whereParam+=" or t1.create_party_id = #{parentId}) ";
            } else {
            	whereParam+=" ) ";
            }
        }
        if (extInformation.getUserId() != null) {
        	whereParam += " and not exists (select 1 from sys_user p1 where t1.create_time>p1.update_time and p1.id=#{userId})";
        }

        String where = " 1=1 "+whereParam;
        String sql = new SQL(){{
            SELECT(select);
            FROM(table);
            WHERE(where);
        }
        }.toString();


        return sql;
    }
}
